package com.huaxin.hxcloud.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.emmp_ard.scancapture.ScanCaptureActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.UserDTO;
import com.huaxin.common.Entity.UserInfo;
import com.huaxin.common.Entity.UserInfoDTo;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ArrangeTaskListActivity;
import com.huaxin.hxcloud.activity.HxScStationTreeListActivity;
import com.huaxin.hxcloud.activity.ModuleItem;
import com.huaxin.hxcloud.activity.ReportActivity;
import com.huaxin.hxcloud.activity.SignActivity;
import com.huaxin.hxcloud.activity.StationListActivity;
import com.huaxin.hxcloud.activity.VehicleMgtActivity;
import com.huaxin.hxcloud.activity.WarningListActivity;
import com.huaxin.hxcloud.work.HxScSyncDataActivty;
import com.huaxindata.im.main.contactview.friend.HxPersonalCenterActivity;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.ContactPerson;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindDimen;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 工作模块
 * Created by Administrator on 2016/9/7.
 */
public class WorkPagerFragment extends BaseFragment implements View.OnClickListener {
    @BindDimen(R.dimen.grid_divider_height)
    int          dividerheight;
    @BindView(R.id.more)
    ImageView    more;
    @BindView(R.id.tv_unread)
    TextView     tvUnread;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.show)
    ImageView    show;
    @BindView(R.id.tv_task)
    TextView     tvTask;
    @BindView(R.id.tv_warning)
    TextView     tvWarning;
    @BindView(R.id.tv_notice)
    TextView     tvNotice;
    @BindView(R.id.tv_report)
    TextView     tvReport;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private Context mContext;

    public HxWorkConfigAdapter mWorkConfigAdapter;
    private List<UserDTO.WorkModuleArrBean> mWorkConfigList = new ArrayList<>();
    private UserDTO mUserDTO;
    //public ArrayList<ModuleItem> datas = new ArrayList<ModuleItem>();

    //临时数据1
    public MyAdapter adapter;
    public ArrayList<ModuleItem> datas = new ArrayList<ModuleItem>();

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_pager_work;
    }

    @Override
    protected void initView(View view) {

        more.setImageResource(R.drawable.icon_sweep_f);
        more.setOnClickListener(this);

        if (UserManager.getPlatformName() != null && !UserManager.getPlatformName().isEmpty()) {
            toolbar.setTitle(UserManager.getPlatformName());
        } else {
            toolbar.setTitle(UserManager.getOrgName());
        }

        toolbar.setNavigationIcon(R.drawable.icon_warning_f);

        mWorkConfigAdapter = new HxWorkConfigAdapter(getContext(), mWorkConfigList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        recyclerView.setHasFixedSize(true);
        //临时数据3
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);

        //recyclerView.setAdapter(mWorkConfigAdapter);
        mUserDTO = Global.user;
        if (Global.userInfo != null) {
            setNum(Global.userInfo);
        }
        mWorkConfigAdapter.setNewData(mUserDTO.getWorkModuleArr());

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    protected void initData() {
        updateView();
        workConfigClick();
        initConfigData();
    }

    /**
     * 临时数据2
     */
    private void initConfigData() {
        if (!datas.isEmpty()) {
            datas.clear();
        }
        datas.add(ModuleItem.WORKTASK);//工单
        //首创 站点
        if (Constant.SCOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            datas.add(ModuleItem.SC_STATION);//站点
        } else {
            datas.add(ModuleItem.STATION);//站点
        }
        datas.add(ModuleItem.REPORT);//故障申报
        //只在水务云平台上显示
        if (Constant.HxOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            datas.add(ModuleItem.COLLECT);//采集终端
        }
        //首创
        if (Constant.SCOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            datas.add(ModuleItem.SC_SYNCDATA);//综合数据
        }
        //spt工作流
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            datas.add(ModuleItem.WORKFLOW);
            datas.add(ModuleItem.SPT_MAINTENANCE);
        } else {
            datas.add(ModuleItem.ATTENDANCE);//考勤
            datas.add(ModuleItem.VEHICLE);//出入车
        }
        //力鼎 预案管理
        if (Constant.LDOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            datas.add(ModuleItem.LD_PLANMANAGER);
            datas.add(ModuleItem.LD_REPOSITORY);
        }
        // datas.add(ModuleItem.PUNCHCARD);//考勤打卡
        adapter.notifyDataSetChanged();
    }

    /**
     * 工单配置点击
     */
    private void workConfigClick() {
        mWorkConfigAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent workIntent = new Intent();
                switch (mWorkConfigAdapter.getData().get(position).getId()) {
                    case 1: //考勤
                        workIntent = new Intent(mContext, SignActivity.class);
                        break;
                    case 2: //工单
                        workIntent = new Intent(mContext, ArrangeTaskListActivity.class);
                        break;
                    case 3://站点
                        if (Constant.SCOrgcodeFirst.equals(mUserDTO.getOrgCode())) {
                            workIntent = new Intent(mContext, HxScStationTreeListActivity.class);
                        } else {
                            workIntent = new Intent(mContext, StationListActivity.class);
                        }
                        break;
                    case 4://出车
                        workIntent = new Intent(mContext, VehicleMgtActivity.class);
                        break;
                    case 5://故障
                        workIntent = new Intent(mContext, ReportActivity.class);
                        break;
                    case 6://综合数据
                        workIntent = new Intent(mContext, HxScSyncDataActivty.class);
                        break;
                    default:
                        break;
                }
                startActivity(workIntent);
            }
        });
    }


    @OnClick({R.id.toolbar, R.id.tv_task, R.id.tv_warning, R.id.tv_notice, R.id.tv_report, R.id.more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar:
                Intent intentWar = new Intent(mContext, WarningListActivity.class);
                intentWar.putExtra("index", 0);
                startActivity(intentWar);
                break;
            case R.id.tv_task://工单
                startActivity(new Intent(getActivity(), ArrangeTaskListActivity.class));
                break;
            case R.id.more:
                //                startActivity(new Intent(getActivity(), ScanCaptureActivity.class));
                startActivityForResult(new Intent(getActivity(), ScanCaptureActivity.class), 0);
                break;
            case R.id.tv_warning://告警
                Intent intent1 = new Intent(mContext, WarningListActivity.class);
                intent1.putExtra("index", 0);
                startActivity(intent1);
                break;
            case R.id.tv_notice://公告
                Intent intent2 = new Intent(mContext, WarningListActivity.class);
                intent2.putExtra("index", 1);
                startActivity(intent2);
                break;
            case R.id.tv_report:
                ReportActivity.start(getActivity(), ReportActivity.TYPE_RECORD);
                break;
        }
    }


    boolean isPause = false;

    @Override
    public void onResume() {
        super.onResume();
        if (isPause) {
            isPause = false;
            updateView();
        }
        //每次加载界面都请求接口，更新工单消息
        userInfo();
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true;
        if (runnable != null) {
            runnable.stop();
        }
    }

    /**
     * 在MsgReceiverService中收到警告或提示更新ui
     */
    public void receivedAnnoWarn() {
        updateView();
    }

    private void updateView() {
        //未读数
        int count = 0;
        /*int count = LocalAnnoStore.getAnnoStore().getCount(1);
        count += LocalWarnStore.getWarnStore().getCount(1);*/
        if (count > 0) {
            tvUnread.setVisibility(View.VISIBLE);
            tvUnread.setText("" + count);
            if (runnable == null) {
                runnable = new AnimationRunnable(tvUnread);
            }
            if (!runnable.isRun()) {
                runnable.start();
            }
        } else {
            tvUnread.setVisibility(View.GONE);
            if (runnable != null) {
                runnable.stop();
            }
            //            more.setImageResource(R.drawable.icon_warning_f);
        }
    }

    AnimationRunnable runnable;

    @Override
    protected void requestData() {
        super.requestData();
        userInfo();
    }

    private void userInfo() {
        if (TextUtils.isEmpty(Global.user.getServerAddress())) {
            return;
        }
        Call<UserInfoDTo> call = HxTransmitRequestHelper.getRequestApi().getUserInfo();
        autoClose(call);
        call.enqueue(new Callback<UserInfoDTo>() {
            @Override
            public void onResponse(Call<UserInfoDTo> call, Response<UserInfoDTo> response) {
                UserInfoDTo userInfoDTO = response.body();
                if (response.isSuccessful() && userInfoDTO != null) {
                    if (userInfoDTO.isSuccessful()) {
                        Global.userInfo = userInfoDTO.getData();
                        setNum(userInfoDTO.getData());
                    }
                } else {
                    ToastUtil.showToastShort(response.errorBody().toString());
                }
            }

            @Override
            public void onFailure(Call<UserInfoDTo> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ----" + t);
            }
        });
    }

    public void setNum(UserInfo userInfo) {
        if (userInfo != null) {
            tvTask.setText((userInfo.getArrangeTaskNum() + ""));//工单
            tvWarning.setText((userInfo.getWarningNum() + ""));//警告
            tvNotice.setText((userInfo.getNoticeNum() + ""));//公告
            tvReport.setText((userInfo.getReportNum() + ""));//申报
        } else {
            emptyUserInfo("0");
        }
    }

    private void emptyUserInfo(String temp) {
        tvTask.setText(temp);//工单
        tvWarning.setText(temp);//警告
        tvNotice.setText(temp);//公告
        tvReport.setText(temp);//申报
    }

    class AnimationRunnable implements Runnable {
        WeakReference<TextView> tag;
        boolean                 run;
        boolean destory = false;
        float current;
        final float MIN_SCALE = .8f;
        final float MAX_SCALE = 1.2f;

        AnimationRunnable(TextView view) {
            tag = new WeakReference<>(view);
        }

        public boolean isRun() {
            return run;
        }

        public void start() {
            run = true;
            new Thread(this).start();
        }

        public void stop() {
            run = false;
        }

        @Override
        public void run() {
            current = MIN_SCALE;
            int flag = 1;
            while (run && !Thread.interrupted()) {
                final TextView view = tag.get();

                if (current > MAX_SCALE) {
                    flag = -1;
                } else if (current < MIN_SCALE) {
                    flag = 1;
                }

                current += flag * 0.02f;

                if (view != null) {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            view.setScaleX(current);
                            view.setScaleY(current);
                            view.invalidate();
                        }
                    });
                } else {
                    destory = true;
                }
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == Activity.RESULT_OK) {
                String dataString = data.getStringExtra("code");
                if (dataString != null) {
                    if (dataString.contains("#&")) {//拼接字符串二维码解析
                        String[] split = dataString.split("#&");
                        if (split.length == 6) {
                            //id  name 图片链接 手机号码
                            ContactPerson person = new ContactPerson(split[2], split[4], split[3], split[5], null, null);
                      /*  ContactInfoDialog dialog = new ContactInfoDialog(getContext());
                        dialog.show(person);*/
                            Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("contact", person);
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        try {
                            String dataStr = data.getStringExtra("code");
                            JSONObject jsonObject = new JSONObject(dataStr);
                            String typeValue = (String) jsonObject.get("typeValue");
                            if (typeValue.equals("fre")) {
                                String nameID = (String) jsonObject.get("nameID");
                                String name = (String) jsonObject.get("name");
                                String phone = (String) jsonObject.get("phone");
                                String imgeUrl = (String) jsonObject.get("imgeUrl");
                                ContactPerson person = new ContactPerson(nameID, imgeUrl, name, phone, "", "");
                                Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("contact", person);
                                intent.putExtras(bundle);
                                getActivity().startActivity(intent);
                            }
                        } catch (Exception e) {

                        }
                    }

                }
            }
        }
    }

    //临时数据3
    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyViewHolder holder = new MyViewHolder(mInflater.inflate(R.layout.item_module, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.update(position);
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.moduleIcon)
            ImageView moduleIcon;
            @BindView(R.id.moduleName)
            TextView  moduleName;
            int position;

            public MyViewHolder(View itemView) {
                super(itemView);
                autoClose(ButterKnife.bind(this, itemView));
                itemView.setOnClickListener(this);

            }

            public void update(int position) {
                ModuleItem data = datas.get(position);
                this.position = position;
                moduleIcon.setImageResource(data.getResIcon());
                moduleName.setText(data.getResName());

            }

            @Override
            public void onClick(View v) {
                ModuleItem data = datas.get(position);
                data.startActivity(getActivity());
            }
        }

    }

}
